<!-- // <script src="const.js"></script> -->
<template>
  <div class="gk-content">
    <gk-title :gk-title="'录入发货信息'" />
    <div>
      <RecordInfo :record-form="recordFormDetail" :record-data="orderBaseInfo">
        <template #recordInfoslot="{}">
          <div class="solt-info">
            <span class="left-span">
              销售产品总数
              <span class="right-span">{{
                orderBaseInfo.orderDetailCount
              }}</span>
            </span>
            <span>
              品种数
              <span>{{ orderBaseInfo.productSpecCount }}</span>
            </span>
            <span>
              金额合计 (元):
              <span>
                <span class="price">{{
                  Number(orderBaseInfo.orderTotalAmount).toFixed(2)
                }}</span>
              </span>
            </span>
          </div>
        </template>
      </RecordInfo>
      <el-editable
        v-loading="tableLoading"
        height="300px"
        class="hospital-edit-box"
        :data="deliveryInfoList"
        :span-method="objectSpanMethod"
        :columns="partDetailsTableData"
      >
        <template slot="default-batchNo" slot-scope="scope">
          <div>
            <el-input
              v-model="scope.row.batchNo"
              maxlength="32"
              placeholder="请输入"
              style="width: 140px"
              :disabled="handleDisabled(scope.row)"
            />
            <el-button
              v-if="scope.row.flag"
              type="primary"
              size="small"
              icon="el-icon-plus"
              circle
              :disabled="handleDisabled(scope.row)"
              @click="addTableRow(scope.row)"
            />
            <el-button
              v-else
              type="primary"
              size="small"
              icon="el-icon-minus"
              circle
              @click="deleteTableRow(scope)"
            />
          </div>
        </template>
        <template slot="default-deliverNums" slot-scope="scope">
          <div>
            <el-input
              v-model.number="scope.row.deliverNums"
              maxlength="20"
              placeholder="请输入"
              style="width: 100px"
              :disabled="handleDisabled(scope.row)"
            />
            {{ scope.row.transforAfterUnit }}
          </div>
        </template>
        <template slot="default-productionDate" slot-scope="scope">
          <div>
            <el-date-picker
              v-model="scope.row.productionDate"
              :disabled="handleDisabled(scope.row)"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期"
            />
          </div>
        </template>
        <template slot="default-validityDate" slot-scope="scope">
          <div>
            <el-date-picker
              v-model="scope.row.validityDate"
              :disabled="handleDisabled(scope.row)"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期"
            />
          </div>
        </template>
        <template slot="default-serialNumber" slot-scope="scope">
          <div>
            <el-input
              v-model="scope.row.serialNumber"
              maxlength="32"
              placeholder="请输入"
              :disabled="handleDisabled(scope.row)"
            />
          </div>
        </template>
        <template slot="default-udi" slot-scope="scope">
          <div>
            <el-input
              v-model="scope.row.udi"
              placeholder="请输入"
              maxlength="128"
              :disabled="handleDisabled(scope.row)"
            />
          </div>
        </template>
        <template slot="default-remark" slot-scope="scope">
          <div>
            <el-input
              v-model="scope.row.remark"
              placeholder="请输入"
              maxlength="256"
              :disabled="handleDisabled(scope.row)"
            />
          </div>
        </template>
      </el-editable>
    </div>
    <el-dialog title="提示" :visible.sync="dialogFormVisible" width="50%">
      <el-form :model="form">
        <el-form-item label="送货人" label-width="80px">
          <el-input v-model="form.concatMan" placeholder="请填写送货人" />
        </el-form-item>
        <el-form-item label="联系方式" label-width="80px">
          <el-input
            v-model="form.concatPhone"
            placeholder="请填写送货人的联系方式"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialogFormVisible">跳 过</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  inputSecDelOrderDetail,
  tempSaveDelOrderDetail,
  refreshTransferUnit,
} from '@const/beforeSettleApi';
import GkTitle from '@components/gk/title/index.vue';
import RecordInfo from '@/moduleComponents/businessClosedLoop/record';
import ElEditable from '@components/el-editable';
import { cloneDeep, hasIn } from 'lodash';
import { partDetailsTableData, recordFormDetail } from './const';

export default {
  components: { ElEditable, GkTitle, RecordInfo },
  data() {
    return {
      id: this.$route.query.id,
      // 表头
      recordFormDetail,
      partDetailsTableData,
      // 表格Loading
      tableLoading: false,
      dialogFormVisible: false,
      // 表格数据
      orderBaseInfo: {},
      deliveryInfoList: [],
      spanArr: [],
      tempData: {
        batchNo: '',
        deliverNums: '',
        productionDate: '',
        validityDate: '',
        serialNumber: '',
        udi: '',
        remark: '',
        flag: false,
      },
      form: {
        concatMan: '',
        concatPhone: '',
      },
    };
  },
  mounted() {
    // console.log('204')
    this.initNav();
    this.getOrderBaseInfoByOrderId(); // 获取订单基本信息
    // console.log(this.$store.state);
  },
  methods: {
    initNav() {
      const btn = {
        type: 'btn',
        arr: [
          { type: 'button', val: '返回', handle: this.back },
          { type: 'primary', val: '刷新单位转换关系', handle: this.refresh },
          { type: 'success', val: '暂时保存', handle: this.temporaryStorage },
          {
            type: 'primary',
            val: '提交信息',
            handle: this.openDialogFormVisible,
          },
        ],
      };
      this.$store.commit('changeLayoutHandle', btn);
    },
    // 获取订单基础信息
    getOrderBaseInfoByOrderId() {
      // console.log('223')
      this.$axios({
        method: 'post',
        url: inputSecDelOrderDetail,
        data: {
          page: this.curPage,
          pageSize: this.pageSize,
          orderId: this.id,
        },
      }).then((res) => {
        const obj = hasIn(res, 'data.payload') ? res.data.payload : {};
        if (obj.sasProductList.length === 0) {
          this.$router.push({
            path: '/distributorSide/businessClosedLoop/list',
          });
        }
        this.orderBaseInfo = obj;
        this.deliveryInfoList = this.formatListData(obj.sasProductList);
        this.getSpanArr(obj.sasProductList);
      });
    },
    formatListData(arr) {
      let p = 0;
      for (let i = 0; i < arr.length; i += 1) {
        const temp = arr[i];
        for (let j = i; j < arr.length; j += 1) {
          if (temp.orderItemId === arr[j].orderItemId && p === 0) {
            this.$set(arr[j], 'flag', true);
            p += 1;
          } else if (temp.orderItemId === arr[j].orderItemId) {
            this.$set(arr[j], 'flag', false);
            p += 1;
          } else {
            p = 0;
            i = j - 1;
            break;
          }
        }
      }
      return arr;
    },
    getSpanArr(data) {
      this.spanArr = [];
      for (let i = 0; i < data.length; i += 1) {
        if (i === 0) {
          this.spanArr.push(1);
          this.pos = 0;
        } else if (data[i].orderItemId === data[i - 1].orderItemId) {
          // 判断当前元素与上一个元素是否相同(第1和第2列)
          this.spanArr[this.pos] += 1;
          this.spanArr.push(0);
        } else {
          this.spanArr.push(1);
          this.pos = i;
        }
      }
    },
    objectSpanMethod({ rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        const row = this.spanArr[rowIndex];
        const col = row > 0 ? 1 : 0;
        return {
          rowspan: row,
          colspan: col,
        };
      }
      return false;
    },
    addTableRow(row) {
      const arr = cloneDeep(this.deliveryInfoList);
      for (let i = arr.length - 1; i < arr.length && i >= 0; i -= 1) {
        const temp = arr[i];
        let p = 0;
        if (temp.orderItemId === row.orderItemId) {
          arr.forEach((res) => {
            if (temp.orderItemId === res.orderItemId) {
              p += 1;
            }
          });
          if (p === 10) {
            this.$message.error('添加的数据不能超过十条！');
            return;
          }
          this.deliveryInfoList.splice(i + 1, 0, { ...temp, ...this.tempData });
          this.getSpanArr(this.deliveryInfoList);
          return;
        }
      }
    },
    deleteTableRow(row) {
      this.deliveryInfoList.splice(row.$index, 1);
    },
    temporaryStorage() {
      if (this.verification(this.deliveryInfoList, false)) {
        this.$axios({
          method: 'post',
          url: tempSaveDelOrderDetail,
          data: {
            ...this.form,
            inputSasOrderList: this.deliveryInfoList,
            hospitalOrderCode: this.orderBaseInfo.hospitalOrderCode,
            orderCode: this.orderBaseInfo.orderCode,
            orderId: this.id,
            operateType: 0, // 状态：0-暂存，1-提交
          },
        })
          .then((res) => {
            if (res.data.code === '0') {
              this.$message.success('暂存成功！');
            } else {
              this.$message.error(res.data.msg);
            }
          })
          .catch(() => {
            // console.log(res)
          });
      }
    },
    submit() {
      if (this.verification(this.deliveryInfoList, true)) {
        this.$axios({
          method: 'post',
          url: tempSaveDelOrderDetail,
          data: {
            ...this.form,
            inputSasOrderList: this.deliveryInfoList,
            hospitalOrderCode: this.orderBaseInfo.hospitalOrderCode,
            orderCode: this.orderBaseInfo.orderCode,
            orderId: this.id,
            operateType: 1, // 状态：0-暂存，1-提交
          },
        })
          .then((res) => {
            if (res.data.code === '0') {
              this.$message.success('提交成功！');
              this.toDetails();
            } else {
              this.$message.error(res.data.msg);
            }
          })
          .catch(() => {
            // console.log(res)
          });
      }
    },
    refresh() {
      this.$axios({
        method: 'post',
        url: refreshTransferUnit,
        data: {
          orderCode: this.orderBaseInfo.orderCode,
        },
      })
        .then((res) => {
          if (res.data.code === '0') {
            this.getOrderBaseInfoByOrderId();
          } else {
            this.$message.error(res.data.msg);
          }
        })
        .catch((res) => {
          this.$message.error(res);
        });
    },
    verification(arr, flag) {
      let p = 0;
      let temp = {};
      for (let i = 0; i < arr.length; i += 1) {
        temp = arr[i];
        if (
          !temp.batchNo &&
          !temp.deliverNums &&
          !temp.productionDate &&
          !temp.validityDate &&
          !temp.serialNumber &&
          !temp.udi &&
          !temp.remark
        ) {
          p += 1;
          // eslint-disable-next-line no-continue
          continue;
        } else if (
          flag &&
          temp.batchNo &&
          temp.deliverNums &&
          temp.productionDate &&
          temp.validityDate &&
          temp.serialNumber &&
          temp.udi &&
          temp.remark
        ) {
          // eslint-disable-next-line no-continue
          continue;
        } else if (
          flag &&
          (temp.batchNo ||
            temp.deliverNums ||
            temp.productionDate ||
            temp.validityDate ||
            temp.serialNumber ||
            temp.udi ||
            temp.remark)
        ) {
          if (temp.batchNo) {
            if (temp.deliverNums) {
              if (temp.validityDate) {
                if (temp.productionDate) {
                  // eslint-disable-next-line no-continue
                  continue;
                } else {
                  this.$message.error('生产日期不能为空！');
                  return false;
                }
              } else {
                this.$message.error('失效日期不能为空！');
                return false;
              }
            } else {
              this.$message.error('本次发货数量不能为空！');
              return false;
            }
          } else {
            this.$message.error('发货批次号不能为空！');
            return false;
          }
        } else if (flag) {
          return false;
        }
      }
      if (!this.handleDisabled(temp) && p === arr.length) {
        this.$message.error('数据不能全部为空！');
        return false;
      }
      return true;
    },
    handleDisabled(obj) {
      if (obj.transforRelation && obj.transforNum) {
        return false;
      }
      return true;
    },
    openDialogFormVisible() {
      this.dialogFormVisible = true;
    },
    closeDialogFormVisible() {
      // this.form = {
      //   concatMan: '',
      //   concatPhone: ''
      // }
      this.submit();
      this.dialogFormVisible = false;
    },
    toDetails() {
      this.$router.push({
        path: '/distributorSide/businessClosedLoop/detail',
        query: {
          orderId: this.id,
        },
      });
    },
    // 点击返回
    back() {
      this.$router.push({
        path: '/distributorSide/businessClosedLoop/list',
      });
    },
  },
};
</script>

<style lang="less">
.hospital-edit-box {
  .has-gutter {
    tr th:nth-child(18),
    th:nth-child(19),
    th:nth-child(20),
    th:nth-child(21) {
      position: relative;
      ::before {
        position: absolute;
        content: '*';
        color: red;
        top: 0;
        left: 0;
      }
      .no-required {
        &::before {
          content: '';
        }
      }
    }
  }
}
.el-date-editor.el-input,
.el-date-editor.el-input__inner {
  width: 100%;
}
</style>
